//
// Created by Chen qin lang on 2018/7/6.
//

#include "WlQueue.h"

WlQueue::WlQueue(WlPlayStat *playStat) {
    this->playStat = playStat;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);


}

WlQueue::~WlQueue() {
    clearQueue();
    if (playStat!=NULL){
        playStat=NULL;
    }
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);

}

void WlQueue::putAvpacket(AVPacket *avPacket) {
    pthread_mutex_lock(&mutex);
    packQueue.push(avPacket);
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
}

int WlQueue::getAvpacket(AVPacket *avPacket) {
    pthread_mutex_lock(&mutex);
    while (playStat != NULL && !playStat->isexit) {
        if (packQueue.size() > 0) {
            AVPacket *packet = packQueue.front();
            //   LOGE("packQueue.front()");
            if (av_packet_ref(avPacket, packet) == 0) {
                //   LOGE("av_packet_ref");
                packQueue.pop();
            }
            av_packet_free(&packet);
            // LOGE("queue__packet_free");
            av_free(packet);
            // LOGE("queue__free");
            // LOGE("从队列里面取出一个AVpacket,还剩余 %d",packQueue.size());
            break;
        } else {
            LOGE("pthread_cond_wait");
            pthread_cond_wait(&cond, &mutex);

        }

    }
    pthread_mutex_unlock(&mutex);
    return 0;
}

int WlQueue::getAvpacketSize() {
    int size = -1;
    pthread_mutex_lock(&mutex);
    size = packQueue.size();
    pthread_mutex_unlock(&mutex);

    return size;
}

void WlQueue::clearQueue() {
    pthread_cond_signal(&cond);//唤醒等待的线程
    pthread_mutex_lock(&mutex);
    while (!packQueue.empty()){
        AVPacket * packett=packQueue.front();
        packQueue.pop();
        av_packet_free(&packett);
        av_free(packett);
        packett=NULL;
    }

    pthread_mutex_unlock(&mutex);
}
